<?php
namespace My\Model;

use Utuo\UtuoModel;
use Home\Logic\GoodsLogic;
use Utuo\DBRW;

class DistributionShopGoodsModel extends UtuoModel {
	
	protected $_auto = array(
		array('create_time', 'time', self::MODEL_INSERT, 'function'),
		array('images', 'getImages', self::MODEL_BOTH, 'callback'),
		array('attrs_cfg', 'getAttrsCfg', self::MODEL_BOTH, 'callback'),
	    array('shipping_config', 'getShippingConfig', self::MODEL_BOTH, 'callback'),
		array('content', 'getContent', self::MODEL_BOTH, 'callback'),
		array('reward_percent', 'getRewardPercent', self::MODEL_BOTH, 'callback'),
		array('reward_percent_dealer', 'getRewardPercentDealer', self::MODEL_BOTH, 'callback'),
		array('only_dealer', 'getOnlyDealer', self::MODEL_BOTH, 'callback'),
		array('try', 'getTry', self::MODEL_BOTH, 'callback'),
	    array('try_reward_red', 'getTryRewardRed', self::MODEL_BOTH, 'callback'),
	    array('efficiency', 'getEfficiency', self::MODEL_BOTH, 'callback'),
	    array('brand', 'getBrand', self::MODEL_BOTH, 'callback'),
	    array('status', 'getStatus', self::MODEL_BOTH, 'callback'),
	    array('is_seckill', 'getIsSeckill', self::MODEL_BOTH, 'callback'),
	    array('currency_enabled', 'getCurrencyEnabled', self::MODEL_BOTH, 'callback'),
	);
	
	// 自动验证
	protected $_validate = array(
	    array('class_id', 'getClassId','当前选择的类目无效', self::EXISTS_VALIDATE, 'callback'),
	);
	
	protected function getCurrencyEnabled() {
	    return $_REQUEST['currency_enabled']?1:0;
	}
	
	/**
	 * 是否为秒杀产品
	 */
	protected function getIsSeckill() {
	    $isSecKill = I("is_seckill", 0, "intval");
	    return $isSecKill;
	}
	
	protected function getClassId() {
	    $classId = I("class_id");
        /*是否可选*/
        $productClass = M("ProductClass")->find($classId);
        if ( $productClass['type'] != \Admin\Model\ProductClassModel::TYPE_ALWAYS_SELECTABLE and $productClass['has_child']!=0 ) {
            return false;
        }
	    return true;
	}
	
	/**
	 * 仅金牌会员可买
	 */
	protected function getTry() {
		$try = I("try");
		return $try*1;
	}
	
	/**
	 * 仅金牌会员可买
	 */
	protected function getTryRewardRed() {
	    $try = I("try_reward_red");
	    return $try*1;
	}
	
	/**
	 * 产品功效
	 * @return boolean
	 */
	protected function getEfficiency() {
	    if(!isset($_REQUEST['efficiency']) or empty($_REQUEST['efficiency'])) return false;
	    $shippingValues = I("efficiency");
	    return join(",", $shippingValues);
	}
	
	/**
	 * 产品品牌
	 * @param unknown $cid
	 * @return boolean|unknown
	 */
	protected function getBrand( $cid ) {
	    $cid = $cid ? $cid : session('id'); // 客户的合作商
	    $brandName = $_REQUEST['brand_name'];
	    $brandSysId = $_REQUEST['brand_sys'];
	    $brand = $_REQUEST['brand'];
	    if( empty($_REQUEST['class_id']) or empty($brandName) or !$cid ) return false;
	    if ( !empty($brand) ) { // 选择了已有品牌处理
	        return $brand;
	    } elseif( !empty($brandSysId) ) { // 选择了系统品牌处理
	        $partnerBrand = M('CustomerBrand')->where('cid=%d and brand=%d', $cid, $brandSysId)->find();
	        if ( !$partnerBrand ) { // 合作商不存在该本牌时添加
	            $bid = M('CustomerBrand')->add(array(
	                'cid' => $cid,
	                'brand' => $brandSysId, ));
	            if ( false !== $bid ){
	                return $bid;
	            }
	        }
	    } elseif(!empty($brandName)) { // 输入品牌处理
	        $partnerBrand = M('CustomerBrand')->where("cid=%d and name='%s'", $cid, $brandName)->find();
	        if( $partnerBrand ) {  // 合作商存在同名品牌
	            return $partnerBrand['id'];
	        } else {
	            $bid = M('CustomerBrand')->add(array(
	                'cid' => $cid,
	                'brand' => 0,
	                'name' => $brandName, ));
	            if ( false !== $bid ){
	                return $bid;
	            }
	        }
	    }
	    return false;
	}
	
	/**
	 * 仅金牌会员可买
	 */
	protected function getOnlyDealer() {
		$onlyDealer = I("only_dealer");
		return $onlyDealer*1;
	}
	
	/**
	 * 返拥金比例
	 */
	protected function getRewardPercent() {
		$rewardPercent = I("reward_percent");
		$rewards = array();
		$tmp = explode(':', $rewardPercent);
		foreach ( $tmp as $v ) {
			if( $v*1 ) {
				$rewards[] = $v*1;
			} else {
				break;
			}
		}
		return join(':', $rewards);
	}
	
	/**
	 * 返拥金比例
	 */
	protected function getRewardPercentDealer() {
		$rewardPercent = I("reward_percent_dealer");
		$rewards = array();
		$tmp = explode(':', $rewardPercent);
		foreach ( $tmp as $v ) {
			if( $v*1 ) {
				$rewards[] = $v*1;
			} else {
				break;
			}
		}
		return join(':', $rewards);
	}
	
	/**
	 * 上传商品的图片
	 * @return boolean|string|NULL
	 */
	protected function getImages() {
		if(!isset($_REQUEST['images'])) return false;
		$images = I("images", null);
		if ( is_array($images)) {
			return serialize($images);
		}
		return null;
	}
	
	/**
	 * 商品的属性配置
	 * @return boolean|string|NULL
	 */
	protected function getAttrsCfg() {
		if(!isset($_REQUEST['attrs_cfg'])) return false;
		$images = I("attrs_cfg", null);
		if ( is_array($images) ) {
			return serialize($images);
		}
		return null;
	}
	
	/**
	 * 商品的属性配置
	 * @return boolean|string|NULL
	 */
	protected function getShippingConfig() {
	    if(!isset($_REQUEST['shipping_config'])) return false;
	    $shippingConfig = I("shipping_config", null);
	    if ( is_array($shippingConfig) ) {
	        return serialize($shippingConfig);
	    }
	    return null;
	}
	
	/**
	 * 商品内容
	 * @return boolean|Ambigous <mixed, NULL, unknown>
	 */
	protected function getContent() {
		if(!isset($_REQUEST['content'])) return false;
		$content = I("content", "", "htmlspecialchars_decode");
		return $content;
	}
	
	/**
	 * 获得用户将要添加到购物车的商品增加购物车中需要的数据
	 * @param int $id 商品id
	 * @param array $attrs 用户选择的商品属性
	 * array(
	 *   '属性名' => '属性值',
	 * )
	 * @return unknown
	 */
	public function getUserSubmitGoods($id, $attrs) {
		$user = session(session('sessionKey'));
		$goods = $this->find($id);
		/* 定时上架商品 */
		if ( $goods ) {
		    if ( !$goods['status'] ) {
		        if ( $goods['timing_shelves'] ) {
		            if ( $goods['timing_shelves'] <= time() ) {
		                M("DistributionShopGoods")->save(array('id'=>$goods['id'], 'timing_shelves'=>0, 'status'=>1));
		                $goods['timing_shelves'] = 0;
		                $goods['status'] = 1;
		            } else {
		                $this->error = '商品还未上架';
		                return false;
		            }
		        }
		        $this->error = '商品已下架';
		        return false;
		    }
		} else {
		    $this->error = '商品已不存在'; 
		    return false;
		}
		
		/* 限购 */
		$orderId = I('orderId', 0, "intval");
		if ( !$orderId ) {
		    $quantity = I ( "quantity", 1, "intval" ) and $quantity === 0 and $quantity = 1;
		    DBRW::openAndClose(0);
		    $goodsSum = M("DistributionShopOrderGoods a")->join("__DISTRIBUTION_SHOP_ORDER__ b on a.order_id=b.id")
		                                                 ->where(array("a.product_id"=>$id, "b.cid"=>$this->cid, "b.uid"=>$user['id'], 
		                                                              "b.order_status"=>array('not in', array(
                                                                          DistributionShopOrderModel::ORDER_STATUS_CANCELED, 
                                                                          DistributionShopOrderModel::ORDER_STATUS_INVALID
                                                                      ))
		                                                        ))
		                                                 ->sum("a.product_number");
		    DBRW::openAndClose(1);
		    if ( $goods['limit_buy'] && (($goodsSum*1 + $quantity) > $goods['limit_buy']*1) ) {
		        $this->error = "每人只能对该商品购买{$goods['limit_buy']}件哦~~";
		        return false;
		    }
		}
		
		/* 商品属性 */
		$goods['attrs_cfg'] = $attributeValues = unserialize($goods['attrs_cfg']);
		$goods['shipping_config'] = unserialize($goods['shipping_config']);
		if ( $attributeValues ) {
			// 验证商品属性选择
			$selectedAttributes = is_array($attrs) ? $attrs : array(); // 用户选择的商品属性
			foreach ($attributeValues as $k => $v) {
				$v = (array)$v;
				if(!isset($selectedAttributes[$k])) { $this->error = "属性:{$k}未选择."; return false;}
				if(!in_array($selectedAttributes[$k], $v)) { $this->error = "属性值:{$selectedAttributes[$k]}未找到."; return false;}
			}
		}
		$goods['images'] = unserialize($goods['images']);
		$goods['pic'] = $goods['images'] ? $goods['images'][0] : '';
		$goods['selectedAttributes'] = $selectedAttributes;
		
		/* 商城配置 */
		$disShopConfig = D("My/DistributionShop")->getShopConfig($goods['cid']);
		
		/* 拍下价格 */
		$goods['productPrice'] = $this->getGoodsPrice($disShopConfig, $goods);
		
		/* 商品积分 */
		$currencyInfo = $this->getGoodsCurrency( $disShopConfig, $goods );
		$goods['rewardCurrency'] = $currencyInfo['rewardCurrency'];
		$goods['currencyValue'] = $currencyInfo['currencyValue'];
		
		return $goods;
	}
	
	/**
	 * 获得实际运费
	 * @param int $id 商品id
	 * @param int $quantity 购买数量
	 */
	public function getShipping($id, $quantity, $tplId, $province, $goodsSnap) {
	    if ( !$goodsSnap ) {
	        $productGoods = $this->find($id);
	        $productGoods['shipping_config'] and $productGoods['shipping_config']  = unserialize($productGoods['shipping_config']);
	    } else {
	        $productGoods = $goodsSnap;
	    }
	    $totalShipping = array();
	    if ( $productGoods['shipping_method']*1 ) {
	        // 免运费
	    } else {
	        if ( $tplId ) { // 有运费模板时
	            /* 计算运费 */
	            $shippingPriceList = GoodsLogic::calcDeliveryFee(array('tplId'=>$tplId), $province, $quantity);
	            /* 汇总运费 */
	            foreach ( $shippingPriceList as $k => $v ) {
	                $totalShipping[$k] += $v;
	            }
	        } else { // 无运费模板时
	            foreach ($productGoods['shipping_config'] as $k => $v) {
	                $v*1 and $totalShipping[$k] += $v*$quantity;
	            }
	        }
	    }
	    return $totalShipping;
	}
	
	/**
	 * 获得商品积分信息
	 * @param $shopCurrencyConfig 商品积分配置
	 * @param $goods 商品拍下时的信息
	 * @return array
	 * array(
	 *    'rewardCurrency' => 0, // 购买后返多少商城币
	 *    'currencyValue' => 0, // 商品的商城币值
	 * )
	 */
	public function getGoodsCurrency( $shopCurrencyConfig=array(), $goods = array() ) {
	    $rewardCurrency = 0; //  购买后返多少商城币
	    $currencyValue = 0; // 商品的商城币值
		if ( $shopCurrencyConfig['currency_config'] ) {
		    if ( isset($shopCurrencyConfig['currency_config']['opened']) and $shopCurrencyConfig['currency_config']['opened'] ) {
		        if ( $goods['currency_enabled'] ) {
		            $shopCurrencyConfig['currency_config']['value'] and $currencyValue = $goods['productPrice']*100/$shopCurrencyConfig['currency_config']['value'];
		        }
		        $rewardCurrency = $goods['reward_currency']; 
		    }
		}
		return array(
		    'rewardCurrency' => $rewardCurrency,
		    'currencyValue' => $currencyValue,
		);
	}
	
	/**
	 * 获得商品单价
	 * @param unknown $goods
	 * @return number
	 */
	private function getGoodsPrice( $disShopConfig, $goods ) {
		$user = session(session('sessionKey'));
		$user = M("WechatUser")->find($user['id']);
		$price = $sourePrice = $goods['price']*1;
		if ( $goods['try'] ) { // 试用商品
			$price = $goods['try_price'];
		} else { // 非试商品
			$userRole = new UserRole();
			$userRole->type($user['type']);
			/* 金牌会员购买价 */
			if ( $userRole->is(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) {
			    if ( $goods['dealer_price']*1 ) { // 设置了金牌会员价
			        $price = $goods['dealer_price']*1;
			    } else { // 未设置金牌会员价
		            if ( $sourePrice > 0.1 ) {
		                if ( $disShopConfig['discount_open'] ) { // 金牌会员折扣
			                $userDiscount = $disShopConfig['user_discount'];
			                if ( $userDiscount ) {
			                    krsort($userDiscount);
			                    foreach ( $userDiscount as $k => $v ) {
			                        if ( $user['sonDealerCount'] >= $v['number'] ) {
			                            $price = sprintf('%.2f', $sourePrice*$v['discount']/100);
			                            break;
			                        }
			                    }
			                }
		                } 
		            }
			    }
			}
		}
		return $price;
	}
	
	/**
	 * 通过上架方式获得商品当前状态qr
	 * @return number
	 */
	protected function getStatus() {
	    $beginMethod = I("begin_method", 0, "intval");
	    $status = 1;
	    if ( $beginMethod == 0 ) {
	        $status = 1;
	    } elseif ( $beginMethod == 1 ) {
	        $status = 0;
	        $_date = I("_date", 0, "htmlspecialchars_decode");
	        $_hour = I("_hour", 0, "intval");
	        $_minute = I("_minute", 0, "intval");
	        $this->tempData['timing_shelves'] = strtotime("{$_date} {$_hour}:{$_minute}:00");
	    } elseif ( $beginMethod == 2 ) {
	        $status = 0;
	    }
	    return $status;
	}
}